import { defineStore } from 'pinia'
import axios from 'axios'

export const useDrugStore = defineStore('drug', {
  state: () => ({
    drugs: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchDrugs() {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get('/getAllDrugs')
        this.drugs = response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch drugs'
        console.error('Error fetching drugs:', error)
      } finally {
        this.loading = false
      }
    },
    
    async addDrug(drug) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/insertDrug', drug)
        await this.fetchDrugs()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to add drug'
        console.error('Error adding drug:', error)
      } finally {
        this.loading = false
      }
    },
    
    async updateDrug(drug) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/updateDrug', drug)
        await this.fetchDrugs()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to update drug'
        console.error('Error updating drug:', error)
      } finally {
        this.loading = false
      }
    },
    
    async deleteDrug(drId) {
      this.loading = true
      this.error = null
      
      try {
        await axios.get(`/deleteDrug/${drId}`)
        await this.fetchDrugs()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to delete drug'
        console.error('Error deleting drug:', error)
      } finally {
        this.loading = false
      }
    }
  }
}) 